$(function () {

    init();
    function init() {
        renderData()
        $(".seachBtn").on("tap", function () {
            var txt = $(".seachTxt").val();
            // console.log(txt);
            if (!$.trim(txt)) {
                // console.log("bhf");
                return;
            }
            //txt存到本底存储中
            var ls = localStorage;
            // console.log(ls);
            var arr = (ls.getItem("letaoHistory") && JSON.parse(ls.getItem("letaoHistory"))) || [];
            // console.log(`arr`);
            for (var i = 0; i < arr.length; i++) {
                var element = arr[i];
                // console.log(element);
                if (element == txt) {
                    /* 已经存在了删除 */
                    // splice 删除数组(索引,要删除几个)
                    arr.splice(i, 1)
                }
            }

            arr.unshift(txt);
            ls.setItem("letaoHistory", JSON.stringify(arr));
            location.href = "./searchList.html?key=" + txt;
        })
        $(".clearAll").on("tap", function () {
            localStorage.removeItem("letaoHistory");
        })
        $(".his_record ul").on("tap", ".removeItem", function (e) {
            // console.log(e);
            var aDom = e.target;
            var index = $(aDom).parent().data("index");
            var ls = localStorage;

            var arr = (ls.getItem("letaoHistory") && JSON.parse(ls.getItem("letaoHistory"))) || [];

            arr.splice(index, 1);

            var str = "";
            for (var i = 0; i < arr.length; i++) {
                var element = arr[i];
                str += ' <li> ' + element + ' <a data-index=' + i + ' class="removeItem mui-pull-right" href="javascript:;"><span class="mui-icon mui-icon-closeempty"></span></a> </li>';
            }
            $(".his_record ul").html(str);

            // 数组存入本地存储中
            ls.setItem("letaoHistory", JSON.stringify(arr));
            
        })
    }

    function renderData() {
        var ls = localStorage;
        var arr = (ls.getItem("letaoHistory") && JSON.parse(ls.getItem("letaoHistory"))) || [];
        var str = "";
        for (var i = 0; i < arr.length; i++) {
            var element = arr[i];
            // console.log(element);
            str += ' <li> ' + element + ' <a data-index=' + i + ' class="removeItem mui-pull-right" href="javascript:;"><span class="mui-icon mui-icon-closeempty"></span></a> </li>';

        }
        $(".his_record ul").html(str);

        if (arr.length > 0) {
            $(".his_info").hide();
        } else {
            $(".his_record").hide();
        }
    }









   
})

